/**
 * @param {number[]} temperatures
 * @return {number[]}
 */
var dailyTemperatures = function (temperatures) {
    let res = new Array(temperatures.length).fill(0),
        stack = [];// 维护一个从栈顶到栈底递增的索引序列

    for (let i = 0; i < temperatures.length; i++) {
        // 栈顶元素小于即将进栈的元素，弹出栈顶，维护res
        while (stack.length >= 0 && temperatures[stack[stack.length - 1]] < temperatures[i]) {
            let topIndex = stack.pop()
            res[topIndex] = i - topIndex
        }
        // 栈顶元素大于或者等于即将进栈的元素，push进去（也可以省略判断条件，直接push）
        if (stack.length === 0 || (stack.length >= 0 && temperatures[stack[stack.length - 1]] >= temperatures[i])) {
            stack.push(i)
        }
    }
    return res
};